<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :title="`${dialogProps.title}餐台`">
    <el-form
      ref="ruleFormRef"
      label-width="110px"
      label-suffix=" :"
      :rules="rules"
      :disabled="dialogProps.isView"
      :model="dialogProps.row"
      :hide-required-asterisk="dialogProps.isView"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="桌台名称" prop="name">
            <el-input v-model="dialogProps.row!.name" placeholder="请填写" clearable></el-input>
          </el-form-item>
          <el-form-item label="标准用餐人数" prop="manQty">
            <el-input-number
              class="w100"
              v-model="dialogProps.row!.manQty"
              placeholder="请填写"
              :controls="false"
              :max="30"
              clearable
            ></el-input-number>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="dialogProps.row!.sort" :controls="false"></el-input-number>
          </el-form-item>
          <el-form-item label="是否快餐台" prop="fastFood">
            <el-radio-group v-model="dialogProps.row!.fastFood">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属区域" prop="typeId">
            <el-select class="w100" v-model="dialogProps.row!.typeId">
              <el-option v-for="item in dialogProps.regData" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="桌台号" prop="number">
            <el-input v-model="dialogProps.row!.number" placeholder="请填写" clearable></el-input>
          </el-form-item>
          <el-form-item label="使用状态" prop="status">
            <el-radio-group v-model="dialogProps.row!.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="默认菜式">
            <ProTable
              height="240"
              :columns="dialogColumns"
              :data="dialogProps.row!.deskFoodList"
              :tool-button="false"
              :pagination="false"
            >
              <template #tableHeader>
                <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openSelectTreeTable()">
                  添加默认菜式
                </el-button>
              </template>
              <template #quantity="scope">
                <el-input-number class="w100" v-model="scope.row.quantity" :controls="false" />
              </template>
              <template #withPerson="scope">
                <el-checkbox v-model="scope.row.withPerson" :true-label="1" :false-label="0" />
              </template>
              <template #required="scope">
                <el-checkbox v-model="scope.row.required" :true-label="1" :false-label="0" />
              </template>
              <template #operation="scope">
                <el-button v-auth="'delete'" type="primary" link :icon="Delete" @click.stop="deleteGoodRow(scope.$index)">
                  删除
                </el-button>
              </template>
            </ProTable>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button v-if="dialogProps.title === '新增'" type="primary" @click="handleSubmit(true)"> 保存并继续新增 </el-button>
      <el-button type="primary" @click="handleSubmit(false)"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="BoardDialog">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Goods } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { Delete, CirclePlus } from "@element-plus/icons-vue";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import { getFoodCategoryList, getGoodsSingleItem } from "@/api/modules/goods";

const rules = reactive({
  name: [{ required: true, message: "桌台名称称必填" }],
  typeId: [{ required: true, message: "桌台区域必选" }],
  // manQty: [{ required: true, message: "用餐人数必填" }],
  number: [{ required: true, message: "桌台号必填" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  regData: any[];
  row: Partial<Goods.ResGoodsCategoryList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const dialogProps = ref<DialogProps>({
  isView: false,
  regData: [],
  title: "",
  row: {}
});

const dialogColumns: ColumnProps<Goods.ResGoodsList>[] = [
  { type: "index", label: "序号", minWidth: 50 },
  { prop: "name", label: "菜品名称", align: "left", minWidth: 140 },
  { prop: "foodSpecName", label: "规格名称", minWidth: 80, align: "left" },
  { prop: "quantity", label: "数量", width: 100 },
  { prop: "withPerson", label: "按开台人数", minWidth: 100 },
  { prop: "required", label: "必选（微餐厅）", minWidth: 120 },
  { prop: "operation", label: "操作", minWidth: 80 }
];

const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = () => {
  const params = {
    title: "选择餐台默认菜式",
    isView: false,
    index: 0,
    mate: "foodSpecId",
    selTags: dialogProps.value.row.deskFoodList.map(im => {
      im.id = im.foodSpecId;
      return im;
    }),
    idName: "foodCategoryId",
    columns: [
      { type: "selection", width: 80 },
      { prop: "name", label: "菜品名称", align: "left" },
      { prop: "foodTypeName", label: "分类" },
      { prop: "foodSpecName", label: "规格" },
      { prop: "posPrice", label: "菜品价格" }
    ],
    treeApi: getFoodCategoryList,
    api: getGoodsSingleItem
  };
  selectTreeTableRef.value?.acceptParams(params);
};

const handleSelectedTreeList = (val: any) => {
  dialogProps.value.row.deskFoodList = val.list.map(im => {
    if (!im.quantity) {
      im.quantity = 1;
      im.withPerson = 0;
      im.required = 0;
      return im;
    } else {
      return im;
    }
  });
};

const deleteGoodRow = (index: number) => {
  dialogProps.value.row.deskFoodList.splice(index, 1);
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;

  if (!dialogProps.value.row!.typeId) {
    dialogProps.value.row!.typeId = dialogProps.value.regData[0].id;
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = (continuous: boolean) => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}餐台成功！` });
      dialogProps.value.getTableList!();
      if (continuous) {
        dialogProps.value.row = {
          status: 1,
          typeId: null,
          manQty: 4,
          sort: 1,
          fastFood: 0,
          deskFoodList: []
        };
      } else {
        dialogVisible.value = false;
      }
    } catch (error) {
      console.log(error);
    }
  });
};

watch(
  () => dialogVisible.value,
  val => {
    if (!val) {
      dialogProps.value.row!.name = "";
      dialogProps.value.row!.typeId = dialogProps.value.regData[0].id;
      dialogProps.value.row!.manQty = 4;
      dialogProps.value.row!.number = "";
      dialogProps.value.row!.fastFood = 0;
      dialogProps.value.row!.status = 1;
      dialogProps.value.row!.deskFoodList = [];
    }
  }
);

defineExpose({
  acceptParams
});
</script>
